package com.zb.controller;

import java.io.File;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.SessionAttributes;
import org.springframework.web.bind.support.SessionStatus;
import org.springframework.web.context.ServletContextAware;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import com.zb.Service.FiletableService;
import com.zb.Service.PowerService;
import com.zb.Service.RecordService;
import com.zb.Service.UserService;
import com.zb.entity.Carinfo;
import com.zb.entity.Department;
import com.zb.entity.Filetable;
import com.zb.entity.Filetype;
import com.zb.entity.Money;
import com.zb.entity.Power;
import com.zb.entity.Role;
import com.zb.entity.User;
import com.zb.util.CCRDFile;
@Controller
@RequestMapping("/user")
@SessionAttributes({ "sys_user" })
public class UserController implements ServletContextAware{
	@Resource
	private UserService userService;
	@Autowired
	private RecordService rs;
	@Autowired
	private PowerService ps;
	
	@ResponseBody
	@RequestMapping(value="leaders",method=RequestMethod.GET)
	public List<User> getLeaderAll(){
		List<User> ulist = userService.getLeaderAll();
		return ulist;
	}

	// 登录
	@RequestMapping(value="login",method=RequestMethod.POST)
	public String toLogin(@RequestParam(value="name",required = true) String name, @RequestParam(value="pwd",required = true) String pwd,ModelMap modelMap) {
		User user = userService.getLogin(name, pwd);
			if (user != null) {
				if (user.getState()==1) {
					modelMap.put("msg", "帐号已封");
					return "login";
				}
				modelMap.put("sys_user", user);
				Power p = ps.getPowerByRoleId(user.getRole().getId());
				if(p.getLoginrecord()==1){
					rs.addRecord(user.getId(), "进行登陆");
				}
				
				return "index";
			} else {
				modelMap.put("msg", "帐号密码不正确");
				return "login";
			}
	}
	//修改密码
	@RequestMapping(params = "op=pwdupdate")
	public String toUpdatePwd(int id,String pwd,String newpwd,ModelMap modelMap){
		User u = userService.getUserById(id);
		if (!u.getPassword().equals(pwd)) {
			modelMap.put("msg", "旧密码不正确请从新输入密码");
			return "pwdupdate";
		}
		u.setPassword(newpwd);
		userService.updateUserPwd(u);
		modelMap.put("msg", "操作成功！");
		return "login";
	}
	// 注销退出
	@RequestMapping(params = "op=ex")
	public String toex(SessionStatus sessionStatus, ModelMap modelMap) {
		sessionStatus.setComplete();
		return "login";
	}
	
	// 用户信息显示
	@RequestMapping(params = "op=page")
	@ResponseBody
	public Map<String, Object> showUser(Integer page, Integer rows,
			String username, String realname) {
		List<User> data = userService.findUserList(page, rows, username,
				realname);
		int count = userService.count();
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("total", count);
		map.put("rows", data);
		return map;
	}

	// 修改用户信息
	
	@RequestMapping(params = "op=updateuser")
	public String updateUser(Integer uid,String name, String pwd, String realname,
			Integer deptname, Integer sex, Integer role, Integer state,
			@RequestParam("file") CommonsMultipartFile file){
		Department department = new Department();
		Role roles = new Role();
		User user = new User();
		user.setId(uid);
		user.setUsername(name);
		user.setPassword(pwd);
		user.setRealname(realname);
		department.setId(deptname);
		user.setDepartment(department);
		user.setGender(sex);
		roles.setId(role);
		user.setRole(roles);
		if (!file.isEmpty()) {
			String path = this.servletContext.getRealPath("/upload/"); // 获取本地存储路径
			System.out.println(path);
			String fileName = file.getOriginalFilename();
			String fileType = fileName.substring(fileName.lastIndexOf("."));
			System.out.println(fileType);
			File file2 = new File(path, new Date().getTime() + fileType); // 新建一个文件
			try {
				file.getFileItem().write(file2); // 将上传的文件写入新建的文件中
			} catch (Exception e) {
				e.printStackTrace();
			}
			user.setImage(path);
		}
		user.setState(state);
		userService.updateUser(user);
		return "usermanager";
	}
	@Autowired
	private FiletableService fts;
	// 添加用户
	@RequestMapping(params = "op=saveuser")
	public String addUser(HttpSession session,String names, String pwds, String realnames,
			Integer deptnames, Integer sexs, Integer roles,
			Integer states, @RequestParam("file") CommonsMultipartFile file) {
		Department department = new Department();
		Role rol = new Role();
		User user = new User();
		user.setUsername(names);
		user.setPassword(pwds);
		user.setRealname(realnames);
		department.setId(deptnames);
		user.setDepartment(department);
		user.setGender(sexs);
		rol.setId(roles);
		user.setRole(rol);
		
		if (!file.isEmpty()) {
			String path = this.servletContext.getRealPath("/upload/"); // 获取本地存储路径
			System.out.println(path);
			String fileName = file.getOriginalFilename();
			String fileType = fileName.substring(fileName.lastIndexOf("."));
			System.out.println(fileType);
			File file2 = new File(path, new Date().getTime() + fileType); // 新建一个文件
			try {
				file.getFileItem().write(file2); // 将上传的文件写入新建的文件中
			} catch (Exception e) {
				e.printStackTrace();
			}
			user.setImage(path);
		}

		user.setState(states);
		userService.saveUser(user);
		User sysuser = (User) session.getAttribute("sys_user");
		rs.addRecord(sysuser.getId(), "添加用户"+user.getRealname());
		
		//用户添加后为用户创建专属文件夹
		Filetable ft = new Filetable();
		Filetable rft = fts.getRootFileByDeptId(user.getDepartment().getId());
		ft.setSecid(rft.getId());
		ft.setName(user.getId()+user.getRealname());
		ft.setFiletype(new Filetype(-1));
		ft.setUser(user);
		ft.setPath(rft.getPath()+user.getId()+user.getRealname()+"/");
		ft.setDepartment(user.getDepartment());
		ft.setTip("备注");
		String realpath = this.servletContext.getRealPath("/文档管理"+ft.getPath());
		if(CCRDFile.createDir(realpath)){
			fts.addFile(ft);
		}else{
			
		}
		
		return "usermanager";
	}

	// 刪除用戶信息
	@RequestMapping(params = "op=delete")
	public String deleteclien(Integer id,ModelMap modelmap) {
		try{
			userService.deleteUser(id);
			modelmap.put("mess", "<script>alert('删除成功！')</script>");
		}catch(Exception e){
			e.printStackTrace();
			modelmap.put("mess", "<script>alert('有外键引用，无法删除')</script>");
		}
		
		return "usermanager";
	}

	// 用户状态
	@RequestMapping(params = "op=state")
	@ResponseBody
	public List<Carinfo> showstate() {
		List<Carinfo> list = new ArrayList<Carinfo>();
		Carinfo c1 = new Carinfo();
		c1.setId(0);
		c1.setCarkind("正常");
		Carinfo c2 = new Carinfo();
		c2.setId(1);
		c2.setCarkind("冻结");
		list.add(c1);
		list.add(c2);
		return list;

	}

	// 用户sex
	@RequestMapping(params = "op=sex")
	@ResponseBody
	public List<Money> showsex() {
		List<Money> list = new ArrayList<Money>();
		Money m1 = new Money();
		m1.setId(0);
		m1.setContent("男");
		Money m2 = new Money();
		m2.setId(1);
		m2.setContent("女");
		list.add(m1);
		list.add(m2);
		return list;

	}

	private ServletContext servletContext;

	public void setServletContext(ServletContext context) {
		this.servletContext = context;
	}
	@RequestMapping(params = "op=deptrole")
	@ResponseBody
	public List<User> getByDR(Integer uid){
		List<User> list=null;
		User u= userService.getUserById(uid);
		
		if(u.getRole().getId()==5){
			list=userService.findUserListByDR(u.getDepartment().getId(), 3);
		}else if(u.getRole().getId()==3){
			list=userService.findUserListByDR(u.getDepartment().getId(), 2);
		}
		
		return list;
	}
}
